package com.hwccl;

import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;

import org.apache.commons.lang.RandomStringUtils;

import com.hwccl.importor.users.model.Users;
import com.hwccl.importor.users.service.UsersLocalServiceUtil;
import com.liferay.portal.NoSuchUserException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.model.User;
import com.liferay.portal.service.OrganizationLocalServiceUtil;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;

/**
 * Portlet implementation class UserInterface
 */
public class UserInterface extends MVCPortlet {
 
	
	public void importAllUsers(ActionRequest request, ActionResponse response)
	throws Exception {

		int companyId=10132;
		int count=UsersLocalServiceUtil.getUsersesCount();
		
		List usersList=UsersLocalServiceUtil.getUserses(0, count);
		

		boolean isExists=false;

    for (int i=0;i<count;i++) {
    	Users user=(Users) usersList.get(i);

        

		try {
			UserLocalServiceUtil.getUserByScreenName(companyId, user.getScreenName());
			
			// Do not populate the sample database if Paul already exists
			System.out.println("User "+ user.getScreenName()+" exists!");
		
			isExists=true;
		}
		catch (NoSuchUserException nsue) {
			isExists=false;
		}
		if (!this.isMail(user.getEmail())) {
			isExists=true;
		}
		if (!isExists) {
			try {
				UserLocalServiceUtil.getUserByEmailAddress(companyId, user.getEmail());
				
				// Do not populate the sample database if Paul already exists
				System.out.println("User "+ user.getScreenName()+" exists!");
			
				isExists=true;
			}
			catch (NoSuchUserException nsue) {
				isExists=false;
			}			
			
		}
	    if (!isExists) {
	    	System.out.println("Start to import "+user.getScreenName());
			long creatorUserId = 0;
			boolean autoPassword = false;
			String password1 = RandomStringUtils.randomNumeric(6);
			String password2 = password1;
			boolean autoScreenName = false;
			String screenName = user.getScreenName();
			String emailAddress = user.getEmail();
			long facebookId = 0;
			String openId = StringPool.BLANK;
			Locale locale = Locale.SIMPLIFIED_CHINESE;
			String firstName = user.getFirstName();
			String middleName = StringPool.BLANK;
			String lastName = user.getLastName();
			int prefixId = 0;
			int suffixId = 0;
			boolean male = true;
			if (user.getMale()==0) 
				{male = false; }
			int birthdayMonth = Calendar.JANUARY;
			int birthdayDay = 1;
			int birthdayYear = 1970;
			String jobTitle = user.getJobtitle();
			long[] groupIds = null;
			long[] organizationIds = null;

			long[] roleIds = null;
			long[] userGroupIds = null;
			boolean sendEmail = true;
		
			ServiceContext serviceContext = new ServiceContext();
		    try {
			User importUser = UserLocalServiceUtil.addUser(
				creatorUserId, companyId, autoPassword, password1, password2,
				autoScreenName, screenName, emailAddress, facebookId, openId,
				locale, firstName, middleName, lastName, prefixId, suffixId, male,
				birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
				organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
			// Assign Business Organization to User
			long buOrg=OrganizationLocalServiceUtil.getOrganizationId(companyId, user.getOrganization());
			long[] userIds={importUser.getUserId()};
			//UserLocalServiceUtil.addOrganizationUsers(buOrg,userIds);
			long deptOrg=OrganizationLocalServiceUtil.getOrganizationId(companyId, user.getDepartment());
			UserLocalServiceUtil.addOrganizationUsers(deptOrg,userIds);
			
			if (_log.isDebugEnabled()) {
				_log.debug(
					importUser.getFullName() + " was created with user id " +
						importUser.getUserId());
			}
	
			_log.info(user.getFirstName() + " " + user.getLastName() + " Imported!" );
			
		    }
			catch (NoSuchUserException nsue) {
				
			}		    

	    }
    }    
    
	/* Placeholder for SessionMessages */

	sendRedirect(request, response);
	}	
	
	private boolean isMail(String str){
		String check = "^([a-z0-9A-Z]+[-|._]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?.)+[a-zA-Z]{2,}$";
		Pattern regex = Pattern.compile(check);
		Matcher matcher = regex.matcher(str.trim());
		boolean isMatched = matcher.matches();
		if(isMatched){
		return true;
		}else{
		return false;
		}
		} 
    
	

private static Log _log = LogFactoryUtil.getLog(
		UserInterface.class);

}
